package handler

import (
	"art-sys/cache"
	"art-sys/model"
	"art-sys/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node11
	model.DB.Table("node11").
		Joins(" JOIN role_nodes ON node11.id=role_nodes.nid").
		Where("role_nodes.nid= ?", rid).Find(&node)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": node,
	})
	return
}

func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var role []model.Role11
	model.DB.Table("role11").
		Joins("JOIN user_roles ON role11.id=user_roles.rid").
		Where("user_roles.uid= ?", uid).Find(&role)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": role,
	})
	return
}

func RoleNode(c *gin.Context) {
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.RoleNode{
		Nid: nid,
		Rid: rid,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户与角色的关联失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "用户与角色的关联成功",
		})
		return
	}
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次,已禁封",
		})
		return
	}
	var user model.User11
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "账号或密码错误三次,禁封两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
